import { ISchema } from "@formily/react";
import { getOptions } from "src/utils";

const namespaceFnSchema = (schemaType: string): ISchema => {
  const componentProps = schemaType === "edit" ? { disabled: true } : {};
  return {
    type: "string",
    title: "Namespace",
    required: true,
    enum: getOptions(["test", "tiktok", "toutiao"]),
    "x-decorator": "FormItem",
    "x-component": "Select",
    "x-component-props": {
      ...componentProps,
      getPopupContainer: (triggerNode: any) => triggerNode.parentElement,
    },
  };
};

const typeFnSchema = (schemaType: string): ISchema => {
  const componentProps = schemaType === "edit" ? { disabled: true } : {};
  return {
    type: "string",
    title: "Type",
    required: true,
    enum: getOptions([
      ["MySQL", "mysql"],
      ["Redis", "redis"],
      ["MongoDB", "mongodb"],
    ]),
    "x-decorator": "FormItem",
    "x-component": "Select",
    "x-component-props": {
      ...componentProps,
      getPopupContainer: (triggerNode: any) => triggerNode.parentElement,
    },
  };
};

const nameFnSchema = (schemaType: string): ISchema => {
  const componentProps = schemaType === "edit" ? { disabled: true } : {};
  return {
    type: "string",
    title: "Name",
    "x-decorator": "FormItem",
    "x-component": "Input",
    "x-component-props": componentProps,
    "x-validator": [
      { required: true },
      {
        pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
        message: "必须以字母开头，且只能包含字母、数字以及下划线",
      },
    ],
  };
};

function getSchema(schemaType: string): ISchema {
  return {
    type: "object",
    properties: {
      namespace: namespaceFnSchema(schemaType),
      type: typeFnSchema(schemaType),
      name: nameFnSchema(schemaType),
      storageUri: {
        type: "string",
        title: "Uri",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Input",
        "x-component-props": { disabled: true },
        // storageUri：值依赖于 namespace、type、name
        "x-reactions": (field) => {
          const namespace = field.query("namespace").value() || "{Namespace}";
          const type = field.query("type").value() || "{Type}";
          const name = field.query("name").value() || "{Name}";

          field.value = `${namespace}-${type}-${name}`;
        },
      },
      description: {
        type: "string",
        title: "Description",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Input",
      },
      owners: {
        type: "array",
        title: "Owners",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Select",
        "x-display": "hidden",
        "x-reactions": (field) => {
          const value = new Set();
          const idcInfosLength = field.query("idcInfos").value()?.length || 0;

          for (let i = 0; i < idcInfosLength; i++) {
            field
              .query(`idcInfos.${i}.owners`)
              .value()
              // eslint-disable-next-line no-loop-func
              ?.forEach((item: string) => value.add(item));
          }
          field.value = [...value];
        },
      },
      idcInfos: {
        type: "array",
        title: "IdcInfos",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "ArrayItems",
        default: [{}],
        items: {
          type: "object",
          properties: {
            formLayout: {
              type: "void",
              "x-component": "FormLayout",
              "x-component-props": {
                labelAlign: "right",
                wrapperAlign: "left",
                labelCol: 6,
                wrapperCol: 18,
              },
              properties: {
                idc: {
                  type: "array",
                  title: "Idc",
                  required: true,
                  "x-decorator": "FormItem",
                  "x-component": "Select",
                  "x-component-props": {
                    mode: "multiple",
                    getPopupContainer: (triggerNode: any) =>
                      triggerNode.parentElement,
                  },
                  enum: getOptions([
                    ["CN", "cn"],
                    ["Maliva", "maliva"],
                    ["I18N", "i18n"],
                    ["BOE", "boe"],
                  ]),
                  // idc: idcInfos下的各个idc不能拥有相同的值
                  "x-reactions": (field) => {
                    const value = field.value;
                    const index = Number(
                      field.path.entire.toString().split(".")[
                        field.path.length - 2
                      ]
                    );
                    const idcInfosLength = field
                      .query("idcInfos")
                      .value().length;

                    const map = {} as Record<string, boolean>;
                    value?.forEach((item: string) => (map[item] = true));
                    let flag = true;

                    for (let i = 0; i < idcInfosLength; i++) {
                      if (index === i) continue;
                      field
                        .query(`idcInfos.${i}.idc`)
                        .value()
                        // eslint-disable-next-line no-loop-func
                        ?.forEach((item: string) => {
                          if (map[item]) flag = false;
                        });

                      if (!flag) {
                        break;
                      }
                    }

                    field.selfErrors = flag
                      ? ""
                      : "IdcInfos下的各个Idc不能选择相同的值";
                  },
                },
                psm: {
                  type: "string",
                  title: "Psm",
                  required: true,
                  "x-decorator": "FormItem",
                  "x-component": "Input",
                  "x-component-props": {
                    placeholder: "example: mysql.tiktok.live_room",
                  },
                  // psm：不同的type，psm的值有不同的要求
                  "x-reactions": (field) => {
                    switch (field.query("type").value()) {
                      case "mysql":
                        const pattern =
                          /^mysql.[a-zA-Z][a-zA-Z0-9_]*.[a-zA-Z][a-zA-Z0-9_]*$/;
                        field.selfErrors =
                          !field.value || pattern.test(field.value)
                            ? ""
                            : "Type为MySQL时，Psm必须以mysql开头，且只能包含字母、数字、下划线";
                        break;

                      default:
                        field.selfErrors = "";
                    }
                  },
                },
                owners: {
                  type: "array",
                  title: "Owners",
                  required: true,
                  "x-decorator": "FormItem",
                  "x-component": "OwnersSelect",
                },
                remove: {
                  type: "void",
                  "x-decorator": "FormItem",
                  "x-component": "ArrayRemoveBtn",
                  "x-component-props": {
                    style: { position: "absolute", right: 0 },
                  },
                },
              },
            },
          },
        },
        properties: {
          add: {
            type: "void",
            title: "添加 IdcInfo",
            "x-component": "ArrayItems.Addition",
            "x-component-props": {
              type: "primary",
            },
          },
        },
      },
    },
  };
}

export default getSchema;
